#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    // 1. 创建/打开文件并写入初始数据
    int fd = open("test1.txt", O_RDWR | O_CREAT | O_TRUNC, 0644);
    if (fd == -1)
    {
        perror("open");
        exit(EXIT_FAILURE);
    }
    write(fd, "Hello Fcntl\n", 12);
    lseek(fd, 0, SEEK_SET); // 重置偏移量

    // 2. 复制文件描述符
    int new_fd = fcntl(fd, F_DUPFD, 0);
    if (new_fd == -1)
    {
        perror("fcntl");
        exit(EXIT_FAILURE);
    }

    // 3. 验证共享偏移量
    char buf[20];
    read(fd, buf, 5); // 从原fd读取5字节
    printf("Original fd read: %.*s\n", 5, buf);

    read(new_fd, buf, 6); // 从新fd继续读取6字节
    printf("Duplicated fd read: %.*s\n", 6, buf);

    // 4. 验证内容一致性
    lseek(fd, 0, SEEK_SET);
    write(new_fd, "UPDATE", 6); // 通过新fd修改内容
    lseek(fd, 0, SEEK_SET);
    read(fd, buf, 10);
    printf("Original fd after update: %.*s\n", 10, buf);

    close(fd);
    close(new_fd);
    return 0;
}